/* 2016/5/2 */
package com.cosmos.pictureswitcher.wallpaper;

import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
import android.widget.Toast;

import com.cosmos.pictureswitcher.R;
import com.cosmos.pictureswitcher.io.FileUtil;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class SwitchWallpaperService extends IntentService {
    private static final String LOG_TAG = SwitchWallpaperService.class.getSimpleName();

    private static final String BACKGROUND_THREAD_NAME = "SwitchWallpaper";

    static final int MSG_STOP_SWITCH = 0;
    static final int MSG_START_SWITCH = 1;

    private static final String listName = "Default";
    private static final int switchInterval = 5000;

    private boolean hasStop;

    //private final Messenger mMessenger = new Messenger(new MessageHandler(this));

    public SwitchWallpaperService() {
        super(BACKGROUND_THREAD_NAME);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(LOG_TAG, "Switch service on create.");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(LOG_TAG, "Switch service on destroy.");
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.d(LOG_TAG, "Switch service on bind.");
        //return mMessenger.getBinder();
        return null;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(LOG_TAG, "Switch service on unbind.");
        return super.onUnbind(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(LOG_TAG, "Switch service on start command.");

        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        startSwitchWallpaper();
    }

    private void startSwitchWallpaper() {
        Log.i(LOG_TAG, "Start switch wallpaper");
        hasStop = false;
        File[] pictureFiles = FileUtil.findPictures(listName);
        File[] switchOrder = generateSwitchOrder(pictureFiles);
        for (int i = 0; (i %= switchOrder.length) < switchOrder.length; i++) {
            if (hasStop) {
                break;
            }
            File pictureFile = switchOrder[i];
            try {
                WallpaperUtil.setWallpaperByFile(this, pictureFile.getAbsolutePath());
            } catch (IOException ex) {
                Log.e(LOG_TAG, "Set wallpaper failed.", ex);
                Toast.makeText(this, R.string.msg_set_wallpaper_failed,
                        Toast.LENGTH_SHORT).show();
            }
            try {
                Thread.sleep(switchInterval);
            } catch (InterruptedException ex) {
                Log.e(LOG_TAG, "Switch wallpaper thread is interrupted.", ex);
            }
        }
    }

    private void stopSwitchWallpaper() {
        hasStop = true;
    }

    private File[] generateSwitchOrder(File[] files) {
        int fileNum = files.length;
        List<File> switchOrderList = new ArrayList<>(fileNum);
        Random random = new Random();
        int index = -1;
        for (int i = 0; i < fileNum; i++) {
            index = random.nextInt(i + 1);
            switchOrderList.add(index, files[i]);
        }
        File[] switchOrderArray = new File[switchOrderList.size()];
        switchOrderArray = switchOrderList.toArray(switchOrderArray);
        return switchOrderArray;
    }

    /**
     * Handler of incoming messages from clients.
     */
    /*private static class MessageHandler extends Handler {
        WeakReference<SwitchWallpaperService> serviceRef;

        MessageHandler(SwitchWallpaperService service) {
            serviceRef = new WeakReference<>(service);
        }

        @Override
        public void handleMessage(Message msg) {
            SwitchWallpaperService service = serviceRef.get();
            switch (msg.what) {
                case MSG_STOP_SWITCH:
                    service.stopSwitchWallpaper();
                    break;
                case MSG_START_SWITCH:
                    service.startSwitchWallpaper();
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }*/
}
